#pragma once
#include "Common.hpp"
#include <cstring>
class InetAddr
{
public:
    InetAddr(){}
    
    InetAddr(struct sockaddr_in& peer)
    {
        SetAddr(peer);
    }

    InetAddr(std::string ip,uint16_t port):_ip(ip),_port(port)
    {
        memset(&_addr,0,sizeof _addr);
        _addr.sin_family=AF_INET;
        inet_pton(AF_INET,ip.c_str(),&_addr.sin_addr);
        _addr.sin_port=htons(port);
    }

    InetAddr(uint16_t port):_ip("0"),_port(port)
    {
        memset(&_addr,0,sizeof _addr);
        _addr.sin_family=AF_INET;
        // inet_pton(AF_INET,ip.c_str(),&_addr.sin_addr);
        _addr.sin_addr.s_addr=INADDR_ANY;
        _addr.sin_port=htons(port);

    }
    void SetAddr(struct sockaddr_in& addr)
    {
        _addr=addr;
        _port = ntohs(_addr.sin_port);
        // _ip = inet_ntoa(_addr.sin_addr);//4字节网络序列,线程不安全
        char ipbuffer[64];
        // inet_pton(AF_INET,ipbuffer,&_addr.sin_addr);
        inet_ntop(AF_INET,&_addr.sin_addr,ipbuffer,sizeof(_addr));
        _ip=ipbuffer;
    }
    std::string IP(){return _ip;}
    uint16_t PORT(){return _port;}
    std::string StringAddrIP(){return _ip;}
    const struct sockaddr_in& Netaddr(){return _addr;}
    const struct sockaddr* CompulsoryNetAddr()
    {
        return (sockaddr*)&_addr;
    }
    socklen_t AddrLen()
    {
        return sizeof _addr;
    }
    ~InetAddr(){}
private:
    struct sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
};